package com.epfresh.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.epfresh.R;
import com.epfresh.activity.HomeSecondAreaActivity;
import com.epfresh.adapter.SecKillTitleAdapter;
import com.epfresh.api.entity.*;
import com.epfresh.api.entity.RequestEntityMap;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.utils.T;
import com.epfresh.bean.SecondKillTime;
import com.epfresh.global.BaseFragment;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import multitype.OnRecyclerViewItemClickListener;
/**
 * Created by wzh on 2016/5/4.
 */
@SuppressLint("ValidFragment")
public class SecondKillFragment extends BaseFragment {


    private RecyclerView recyclerView;
    SecKillTitleAdapter adapterSecKill;
    //SecondListFragment[] fragments;
    private ViewPager vp;

    protected View mainView;
    protected View vException;
    protected TextView tvExceptionDescription;
    protected ImageView ivExceptionIcon;
    private ProgressBar pb;
    Context mContext;

    String storeId,endTime,sysDate;
    int status;

    public SecondKillFragment() {
    }
    public SecondKillFragment(String storeId, String endTime, int status) {
        this.storeId = storeId;
        this.endTime = endTime;
        this.status = status;
    }

    @Override
    public String getBaseTag() {
        return "SecondKillFragment";
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_second_kill, container, false);
        mContext = this.getActivity();
        initView(view);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        requestTimeList();
    }

    void initView(View v){

        recyclerView = (RecyclerView) v.findViewById(R.id.ly_navigation);

        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerView.setLayoutManager(layoutManager);

        adapterSecKill = new SecKillTitleAdapter();
        recyclerView.setAdapter(adapterSecKill);
        adapterSecKill.setOnRecyclerViewItemClickListener(new OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int i, Object o) {
                vp.setCurrentItem(i);
            }
        });
        adapterSecKill.setCategory(beanList);
        vp = (ViewPager) v.findViewById(R.id.vp);
    }

    int scrollFlag ;

    boolean todayFlag;
    int positionFlag;
    public void loadView() {
        for (int i = 0; i < beanList.size(); i++) {
            if(beanList.get(i).getStatus()==2&&todayFlag == false){
                todayFlag = true;
                positionFlag = i;
                beanList.get(i).setSelectNumber(i);
                break;
            }if(beanList.get(i).getStatus()==1&&todayFlag == false){
                todayFlag = true;
                positionFlag = i;
                beanList.get(i).setSelectNumber(i);
                break;
            }
            if(i==beanList.size()-1){
                positionFlag = i;
                beanList.get(i).setSelectNumber(i);
            }
        }
        if(beanList==null||beanList.size()==0){
            //setContentView(R.layout.empty_goods);
            return;
        }
        adapterSecKill.notifyDataChanged();
        setAdapter();
        vp.setCurrentItem(positionFlag);
        Log.e("positionFlag","______________"+(positionFlag));

        if (positionFlag > 2) {
            recyclerView.scrollToPosition(positionFlag - 1);
            Log.e("scrollto","______________"+(positionFlag-1));
            //layoutManager.scrollToPositionWithOffset(items.indexOf(bean.getMarketAreasBean()),0);
        }
        vp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                scrollFlag = position;

            }

            @Override
            public void onPageSelected(int position) {

                beanList.get(position).setSelectNumber(position);
                adapterSecKill.notifyDataSetChanged();
                recyclerView.scrollToPosition(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        //进行中的显示在中间
        showListPosition();
    }

    private void showListPosition(){
        if(beanList==null || beanList.size()<=3) {
            return;
        }
        for(int i=0;i<beanList.size();i++){
            if(i>1&&beanList.get(i).getStatus()==2){
                recyclerView.scrollToPosition(i-1);
                return;
            }
        }
    }



    private PagerAdapter pagerAdapter;

    public void setAdapter() {
        if(pagerAdapter==null){
            pagerAdapter = new FragmentStatePagerAdapter(getActivity().getSupportFragmentManager()) {
                @Override
                public Fragment getItem(int position) {
                    SecondListFragment secondListFragment = new SecondListFragment(storeId,beanList.get(position).getBegin_time(),beanList.get(position).getEnd_time(),beanList.get(position).getStatus());
                    secondListFragment.setSecondKillFragment(SecondKillFragment.this);
                    return secondListFragment;
                }

                @Override
                public int getCount() {
                    return beanList.size();
                }

                @Override
                public int getItemPosition(Object object) {
                    return POSITION_NONE;
                }

            };
            vp.setAdapter(pagerAdapter);
        }else{
            pagerAdapter.notifyDataSetChanged();
        }
    }



    private List<SecondKillTime.SeckillTimeBean> beanList = new ArrayList<>();

    public void requestTimeList() {
        RequestEntityPurchase<Map<String, Object>> requestEntity = new RequestEntityPurchase<>();
        Map<String, Object> map = new HashMap<>();
        String seckillStoreId = null;
        if (getAppActivity() != null && getAppActivity() instanceof HomeSecondAreaActivity){
            seckillStoreId = ((HomeSecondAreaActivity)getAppActivity()).seckillStoreId;
        }
        map.put("storeId",seckillStoreId);
        requestEntity.setParameters(map);
        requestEntity.setCmd(com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_store_promotion_seckillTime);
        request(requestEntity, com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_store_promotion_seckillTime, new OnRequestListener<SecondKillTime>() {
            @Override
            public SecondKillTime jsonToObj(String s) {
                return new Gson().fromJson(s, SecondKillTime.class);
            }

            @Override
            public void onFail(int i, Object o, Object o1) {
                hideProgressDialog();
                //setContentView(R.layout.error_view);
            }

            @Override
            public void onResponseError(int i, Object o, Object o1) {
                hideProgressDialog();
                //setContentView(R.layout.error_view);
            }

            @Override
            public void onStart(Object o) {
                //showProgressView();
            }

            @Override
            public void onResponse(ResponseEntity<SecondKillTime> responseEntity, Object o) {
                hideProgressDialog();
                //showMainView();
                SecondKillTime secondKillTime = responseEntity.getResponseElement();
                List<SecondKillTime.SeckillTimeBean>list = secondKillTime.getSeckillTime();
                beanList.clear();
                if(list.size()>0){
                    beanList.addAll(list);
                    loadView();
                    return;
                }
                //showExceptionView(R.mipmap.order_no, "获取数据错误", 1);
                T.toast("数据加载失败,请重试");
            }
        });
    }

}